import { log } from 'node:console'
import { copyFileSync, cpSync, existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { manifest } from './manifest'

const outputDir = 'dist/wangyjhh_theme'
const filesToCopy = ['LICENSE']

// 检查是否存在outputDir目录，如果不存在则创建
if (!existsSync(outputDir)) {
    mkdirSync(outputDir, { recursive: true })
}
else {
    // 如果存在则删除目录下的所有文件
    rmSync(outputDir, { recursive: true, force: true })
    mkdirSync(outputDir)
}

// Release
filesToCopy.forEach((file) => {
    // 复制文件到outputDir目录
    const sourcePath = resolve('src', file === 'LICENSE' ? '../LICENSE' : file)
    const destPath = resolve(outputDir, file)
    copyFileSync(sourcePath, destPath)
})

// 去除manifest.json中字段的空值
manifest.theme.images = Object.fromEntries(Object.entries(manifest.theme.images).filter(([_, v]) => v !== '')) as any
manifest.theme.colors = Object.fromEntries(Object.entries(manifest.theme.colors).filter(([_, v]) => v !== '')) as any

// 生成manifest.json文件
writeFileSync(resolve(outputDir, 'manifest.json'), JSON.stringify(manifest, null, 4))

// 复制images目录到outputDir目录
cpSync(resolve('src', 'images'), resolve(outputDir, 'images'), { recursive: true, force: true })

log('Release completed.')
